//
// Created by haoy on 2017/7/27.
//


#include "nack_handler.hpp"

#include "rtp_history.hpp"
#include "xm_log.h"


class nack_handler {
public:
    int64_t last_req_time = 0;
    NAckList nackList;
};

nack_handler_t nack_handler_new() {
    return new nack_handler();
}

void nack_handler_delete(nack_handler_t handler) {
    delete handler;
}

void nack_handler_receive_seq(nack_handler_t handler, int64_t now_ms, uint16_t seq, std::list<nack_request> &reqs) {
    int64_t elapsed = now_ms - handler->last_req_time;
    if(elapsed < 50){
        handler->nackList.addSeq(seq, [&](uint16_t pid, uint16_t blp){
            reqs.emplace_back(pid, blp);
        });
    }else{
        handler->nackList.addSeq(seq, nullptr);
        handler->nackList.extract([&](uint16_t pid, uint16_t blp){
            reqs.emplace_back(pid, blp);
        });
    }
    handler->last_req_time = now_ms;
}

void nack_handler_search_request(nack_handler_t handler, std::list<nack_request> &reqs) {
    handler->nackList.extract([&](uint16_t pid, uint16_t blp){
        reqs.emplace_back(pid, blp);
    });
}



//class nack_handler {
//public:
//    RtpHistory<256> recv_history;
//
//};
//
//nack_handler_t nack_handler_new() {
//    return new nack_handler();
//}
//
//void nack_handler_delete(nack_handler_t handler) {
//    delete handler;
//}
//
//void nack_handler_receive_seq(nack_handler_t handler, uint16_t seq) {
//    handler->recv_history.add_seq(seq);
//}
//
//void nack_handler_search_request(nack_handler_t handler, std::list<nack_request> &reqs) {
//    auto lost = handler->recv_history.search_consecutive_lost(17);
//    while (lost.second != 0) {
//        uint16_t first = lost.first;
//        int count = lost.second;
//
//        if (count == 0) {
//            return;
//        }
//
//        std::bitset<16> blp;
//        for (int i = 0; i < count-1; i++) {
//            blp.set(i);
//        }
//
//        reqs.emplace_back(first, (uint16_t)blp.to_ulong());
//        dbgi("generated nack: pid=%u, blp=%04X", first, (uint16_t)blp.to_ulong());
//        lost = handler->recv_history.search_consecutive_lost(first+count, 17);
//    }
//}

